<?php
namespace app\api\controller;

use app\lib\Show;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Log;

class User extends Auth {

    public function index() {
        return show(config("status.success"), "", $this->user);
    }

    public function update() {
        $data["username"] = $this->request->param("username", "", "trim");
        $data["name"] = $this->request->param("name", "", "trim");
        $data["sex"] = $this->request->param("sex", "", "trim");
        $data["birthday"] = $this->request->param("birthday", "", "trim");
        $data["token"] = $this->user["token"];
        try{
            validate(\app\api\validate\User::class)->scene("updateUserInfo")->check($data);
        }catch (ValidateException $e){
            return show(config("status.error"), $e->getMessage());
        }

        try{
            $result = \app\api\business\User::update($data);
            if (!$result) {
                return show(config("status.error"), "修改失败，请重新提交");
            }
        }catch (Exception $e){
            return show(config("status.error"), $e->getMessage());
        }


        return show(config("status.success"), "修改成功");
    }

    public function init() {
        $userId = $this->user["id"];

        try{
            $result = (new \app\api\business\User())->init($userId);
            return Show::success("ok", $result);
        }catch(Exception $e){
            Log::error($e);
            return Show::fail("用户初始化数据失败");
        }
    }
}